/**
 * 多边形
 *
 * */

#ifndef __POLYGON_H__
#define __POLYGON_H__
#include <GL/glut.h>
#include <list>
#include "point.h"
#include "line.h"
#include "log.h"

/**
 * 多边形类
 * */
template <typename V>
struct Polygon
{
    typedef std::list<Point<V>> Vertices;
    typedef std::list<Line<V>> Lines;

    // 多边形边界(外接矩形)
    V bottom, top, left, right;
    // 多边形的顶点
    Vertices vertices = Vertices();
    // 给多边形增加顶点
    void addPoint(const Point<V> p)
    {

        // 获得边界
        if (vertices.empty())
        {
            log_m("Empty vertices %s\n", "");
            bottom = top = p.y;
            left = right = p.x;
        }
        else
        {
            top = p.y > top ? p.y : top;
            bottom = p.y < bottom ? p.y : bottom;
            left = p.x < left ? p.x : left;
            right = p.x > right ? p.x : right;
        }
        vertices.push_back(p);
        log_m(" l=%g, r=%g, b=%g, t=%g \n", (double)left, (double)right, (double)bottom, (double)top);
    }
    // 绘制多边形的边
    void drawEdge()
    {
        glBegin(GL_LINES);
        for (typename Vertices::iterator iter = this->vertices.begin(); iter != this->vertices.end();)
        {
            glVertex2i(iter->x, iter->y);
            if (++iter == this->vertices.end())
            {
                glVertex2i(this->vertices.begin()->x, this->vertices.begin()->y);
            }
            else
            {
                glVertex2i(iter->x, iter->y);
            }
        }
        glEnd();
    }
    // 返回边的list
    Lines getEdges()
    {
        Lines lines;
        Point<V> t;
        for (typename Vertices::iterator iter = this->vertices.begin(); iter != this->vertices.end();)
        {
            t = *iter;
            if (++iter == this->vertices.end())
            {
                lines.push_back(
                    Line<V>(t, *(this->vertices.begin())));
            }
            else
            {
                lines.push_back(Line<V>(t, *iter));
            }
        }
        return lines;
    }

    bool isPointInside(Point<V> const &p)
    {
        return !((p.x>right) || (p.x<left)||(p.y>top)||(p.y<bottom));
    }
};

#endif // !__POLYGON_H__